package com.example.springboot.service.impl;

import com.example.springboot.dao.UsersDao;
import com.example.springboot.entity.Users;
import com.example.springboot.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public class UserServiceImpl implements UsersService {
    @Autowired
    private UsersDao usersDao;

    @Override
    public List<Users> queryClient() {
        // 返回所有顾客信息
        return usersDao.queryClient();
    }

    @Override
    public List<Users> queryRepair() {
        // 返回所有维修人员信息
        return usersDao.queryRepair();
    }

    @Override
    public Users queryUserById(int userId) {
        // 通过用户id返回信息
        return usersDao.queryUserById(userId);
    }

    @Transactional  //加上事务控制  当抛出RuntimeException异常  事务就会回滚
    @Override
    public boolean insertUser(Users user) {
        if (user.getUserName() != null &&
                user.getUserPhone() != null && user.getUserIdentity() != null)
            try{
                boolean flag = usersDao.insertUser(user);
                if(flag)
                    return true;
                else{
                    throw new RuntimeException("添加用户失败");
                }
            }catch (Exception e){
                throw new RuntimeException("添加用户失败" + e.toString());
            }
        else
            throw new RuntimeException("用户电话或身份不能为空");
    }

    @Transactional
    @Override
    public boolean updateUser(Users user) {
        if(user.getUserId()>0){
            try{
                if(usersDao.updateUser(user)){
                    return true;
                }
                else {
                    throw new RuntimeException("用户更新失败");
                }
            }catch (Exception e){
                throw new RuntimeException("用户更新失败"+e.toString());
            }
        }
        else {
            throw new RuntimeException("用户ID不为空，且要大于0");
        }
    }

    @Transactional
    @Override
    public boolean delUser(int userId) {
        if(userId > 0){
            try{
                if(usersDao.delUser(userId)){
                    return true;
                }else{
                    throw new RuntimeException("删除失败");
                }
            }catch (Exception e){
                throw new RuntimeException("删除失败"+e.toString());
            }
        }else{
            throw  new RuntimeException("用户id不合法");
        }
    }
}
